import { request } from '@umijs/max';
import { METHOD_TYPE } from '@/options';
import { SortOrder } from 'antd/lib/table/interface';
import { StrUtil } from '@/util/msg';
import { BaseListUrl, PageType, Result, ResultPage } from '@/types/common/request';

const useBaseRequest = <DataType, Params>(ApiUrl: string) => {
  /** 获取列表 */
  const getList = async (
    params?: Partial<Params> & PageParams,
    sort?: Record<string, SortOrder>,
    filter?: Record<string, (string | number)[] | null>,
    options?: { [key: string]: any },
  ): Promise<PageType<DataType>> => {
    if (sort && Object.keys(sort).length > 0 && params) {
      let keys: string[] = [],
        orders: string[] = [];
      Object.keys(sort).forEach((key) => {
        keys.push(key);
        orders.push(sort[key] === 'ascend' ? '1' : '-1');
      });
      params.sort = keys.join(StrUtil.COMMIT);
      params.order = orders.join(StrUtil.COMMIT);
    }
    const ret = await request<ResultPage<DataType>>(ApiUrl + BaseListUrl.LIST, {
      method: METHOD_TYPE.GET,
      params: {
        current: 1,
        pageSize: -1,
        ...params,
      },
      ...(options || {}),
    });
    return {
      success: ret.success,
      message: ret.message,
      code: ret.code,
      ...ret.data,
    };
  };

  /** 新增列表 */
  function addItem(data: DataType, options?: { [key: string]: any }) {
    return request<Result<boolean>>(ApiUrl + BaseListUrl.INSERT, {
      method: METHOD_TYPE.POST,
      data,
      ...(options || {}),
    });
  }

  /** 修改列表 */
  function updateItem(data: DataType, options?: { [key: string]: any }) {
    return request<Result<boolean>>(ApiUrl + BaseListUrl.UPDATE, {
      method: METHOD_TYPE.PUT,
      data,
      ...(options || {}),
    });
  }

  /** 删除列表 */
  function delItem(id: string, options?: { [key: string]: any }) {
    return request<Result<boolean>>(ApiUrl + BaseListUrl.DELETE, {
      method: METHOD_TYPE.DELETE,
      params: { id },
      ...(options || {}),
    });
  }

  /** 详情 GET  */
  async function detailItem(id: string, options?: { [key: string]: any }): Promise<DataType> {
    const ret = await request<Result<DataType>>(ApiUrl + BaseListUrl.DETAIL, {
      method: METHOD_TYPE.GET,
      params: { id },
      ...(options || {}),
    });
    return ret.data;
  }

  return {
    getList,
    addItem,
    updateItem,
    delItem,
    detailItem,
  };
};

export default useBaseRequest;
